<template>
  <div class="round-manage p-4" tabindex="0">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-input
        v-model="queryParams.roundName"
        placeholder="请输入轮次名称"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd" ref="addButton">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
      <el-button
        type="danger"
        plain
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column prop="name" label="轮次名称" min-width="120" />
      <el-table-column
        prop="maxNum"
        label="选课最大数"
        width="100"
        align="center"
      />
      <el-table-column prop="startTime" label="开始时间" min-width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" min-width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.states === 1 ? 'success' : 'info'">
            {{ scope.row.states === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <div class="flex space-x-2">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              plain
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 轮次添加/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="dialogTitle"
      :direction="direction"
      size="380px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="roundFormRef"
        :model="roundForm"
        :rules="roundFormRules"
        label-width="100px"
        @keyup.enter.native="submitForm"
      >
        <el-form-item label="轮次名称" prop="name">
          <el-input
            v-model="roundForm.name"
            placeholder="请输入轮次名称"
            @keyup.enter="submitForm"
          />
        </el-form-item>
        <el-form-item label="选课最大数" prop="maxNum">
          <el-input-number
            v-model="roundForm.maxNum"
            :min="1"
            :max="20"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="roundForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="roundForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="states">
          <el-radio-group v-model="roundForm.states">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            ref="submitButton"
            @keyup.enter="submitForm"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 轮次详情对话框 -->
    <el-dialog title="轮次详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="轮次ID">{{
          roundDetail.id
        }}</el-descriptions-item>
        <el-descriptions-item label="轮次名称">{{
          roundDetail.name
        }}</el-descriptions-item>
        <el-descriptions-item label="选课最大数">{{
          roundDetail.maxNum
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="roundDetail.states === 1 ? 'success' : 'info'">
            {{ roundDetail.states === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{
          roundDetail.startTime
        }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{
          roundDetail.endTime
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{
          roundDetail.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{
          roundDetail.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {
  getroundlist,
  createround,
  updateround,
  deleteround,
} from '@/api/round'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roundName: '',
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const jumpPage = ref(1)
const addButton = ref(null)
const selectedRows = ref([])

// 抽屉相关
const drawerVisible = ref(false)
const dialogTitle = ref('添加轮次')
const direction = ref('rtl') // 从右向左打开
const isEdit = ref(false)
const roundFormRef = ref(null)
const roundForm = reactive({
  name: '',
  maxNum: 5,
  startTime: '',
  endTime: '',
  states: 1,
})
const submitButton = ref(null)

// 详情对话框
const detailDialogVisible = ref(false)
const roundDetail = reactive({
  id: '',
  name: '',
  maxNum: 0,
  startTime: '',
  endTime: '',
  states: 1,
  createTime: '',
  updateTime: '',
})

// 表单验证规则
const roundFormRules = {
  name: [
    { required: true, message: '请输入轮次名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  maxNum: [{ required: true, message: '请输入选课最大数', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  states: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 格式化日期时间，去除T和Z
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  return dateTimeString.replace('T', ' ').replace(/\.000Z$/, '')
}

// 获取轮次列表
const getRoundList = async () => {
  loading.value = true
  try {
    const { code, data, msg } = await getroundlist(queryParams)
    if (code != 200) {
      throw new Error(msg)
    }
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getRoundList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getRoundList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getRoundList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getRoundList()
}

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加轮次'
  isEdit.value = false
  // 重置表单
  roundForm.id = undefined
  roundForm.name = ''
  roundForm.maxNum = 5
  roundForm.startTime = ''
  roundForm.endTime = ''
  roundForm.states = 1
  drawerVisible.value = true
  // 在表单显示后重置校验结果
  setTimeout(() => {
    roundFormRef.value?.resetFields()
  }, 0)
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑轮次'
  isEdit.value = true
  // 填充表单数据
  roundForm.id = row.id
  roundForm.name = row.name
  roundForm.maxNum = row.maxNum
  roundForm.startTime = row.startTime
  roundForm.endTime = row.endTime
  roundForm.states = row.states
  drawerVisible.value = true
}

// 处理详情
const handleDetail = (row) => {
  // 填充详情数据
  const formattedRow = { ...row }
  if (formattedRow.startTime) {
    formattedRow.startTime = formatDateTime(formattedRow.startTime)
  }
  if (formattedRow.endTime) {
    formattedRow.endTime = formatDateTime(formattedRow.endTime)
  }
  Object.assign(roundDetail, formattedRow)
  detailDialogVisible.value = true
}

// 处理提交表单
const submitForm = async () => {
  if (!roundFormRef.value) return

  await roundFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化日期时间
        if (roundForm.startTime) {
          if (typeof roundForm.startTime === 'object') {
            roundForm.startTime = roundForm.startTime
              .toISOString()
              .replace('T', ' ')
              .replace(/\.000Z$/, '')
          }
        }
        if (roundForm.endTime) {
          if (typeof roundForm.endTime === 'object') {
            roundForm.endTime = roundForm.endTime
              .toISOString()
              .replace('T', ' ')
              .replace(/\.000Z$/, '')
          }
        }

        if (isEdit.value) {
          // 修改
          const { code, msg } = await updateround(roundForm)
          if (code !== 200) {
            throw new Error(msg)
          }
        } else {
          // 添加
          const { code, msg } = await createround(roundForm)
          if (code !== 200) {
            throw new Error(msg)
          }
        }

        ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
        drawerVisible.value = false
        getRoundList()
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除轮次"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const { code, msg } = await deleteround([row.id])
        if (code !== 200) {
          throw new Error(msg)
        }

        ElMessage.success('删除成功')
        getRoundList()
      } catch (error) {
        ElMessage.error(error.message)
      }
    })
    .catch(() => {})
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的轮次')
    return
  }

  const names = selectedRows.value.map((item) => item.name).join('、')
  ElMessageBox.confirm(`确定要删除以下轮次吗？\n${names}`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 收集所有选中行的id
        const ids = selectedRows.value.map((item) => item.id)
        const { code, msg } = await deleteround({ ids })
        if (code !== 200) {
          throw new Error(msg)
        }

        ElMessage.success('批量删除成功')
        getRoundList()
      } catch (error) {
        ElMessage.error(error.message || '批量删除失败')
      }
    })
    .catch(() => {})
}

// 监听roundName变化，实现防抖搜索
let searchTimer = null
watch(
  () => queryParams.roundName,
  (newVal) => {
    if (searchTimer) clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
      handleSearch()
    }, 500) // 500毫秒防抖
  }
)

onMounted(() => {
  getRoundList()
})
</script>

<style lang="less" scoped>
.round-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}
</style>
